package com.digitalchina.lxnsy.activity.old;

import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessRealTimePrice;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PackingVO;
import com.digitalchina.lxnsy.entity.RealPriceDetailsVO;
import com.digitalchina.lxnsy.entity.RealTimeListVO;
import com.digitalchina.lxnsy.entity.RealTimePriceVO;
import com.digitalchina.lxnsy.entity.StandardVO;
import com.digitalchina.lxnsy.entity.StorageModeVO;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.view.MyMarkerView;
import com.digitalchina.lxnsy.viewholder.BaggingHolder;
import com.digitalchina.lxnsy.viewholder.StorageHolder;
import com.digitalchina.lxnsy.widget.ListPopWindow;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/3/16 11:07
 * 修改备注：
 * ================================================
 */

public class RealTimePriceDetailsActivity extends BaseActivity {
    @Bind(R.id.price_detail_iv_update_date)
    TextView priceDetailIvUpdateDate; // 数据更新时间
    @Bind(R.id.price_detail_tv_wholesale_market)
    TextView priceDetailTvWholesaleMarket; // 批发市场名字
    @Bind(R.id.price_detail_tv_highest_price)
    TextView priceDetailTvHighestPrice; // 最高价格
    @Bind(R.id.price_detail_tv_up_number)
    TextView priceDetailTvUpNumber; // 上升数据
    @Bind(R.id.price_detail_tv_up_percent)
    TextView priceDetailTvUpPercent; // 上升百分比
    @Bind(R.id.price_detail_tv_lowest_price)
    TextView priceDetailTvLowestPrice; // 最低价格
    @Bind(R.id.price_detail_tv_down_number)
    TextView priceDetailTvDownNumber; // 下降数据
    @Bind(R.id.price_detail_tv_down_percent)
    TextView priceDetailTvDownPercent; // 下降百分比
    @Bind(R.id.price_detail_iv_left)
    ImageView priceDetailIvLeft; // 向左选择规格
    @Bind(R.id.price_detail_tv_standard)
    TextView priceDetailTvStandard; // 规格
    @Bind(R.id.price_detail_iv_right)
    ImageView priceDetailIvRight; // 向右选择规格
    @Bind(R.id.price_detail_tv_details_data)
    TextView priceDetailTvDetailsData; // 详细数据
    @Bind(R.id.line_chart)
    LineChart mChart; // 图表
    @Bind(R.id.price_detail_tv_bagging)
    TextView priceDetailTvBagging; // 套袋
    @Bind(R.id.price_detail_tv_storage)
    TextView priceDetailTvStorage; // 存贮
    @Bind(R.id.layout_real_time_price_tv_week)
    TextView layoutRealTimePriceTvWeek; // 周
    @Bind(R.id.layout_real_time_price_tv_month)
    TextView layoutRealTimePriceTvMonth; // 月
    @Bind(R.id.layout_real_time_price_tv_custom)
    TextView layoutRealTimePriceTvCustom; // 自定义

    private TimePickerView pvStartTime; // 自定义开始日期
    private TimePickerView pvEndTime; // 自定义结束日期
    private String mStartDate = "", mEndDate = ""; // 自定义开始结束时间

    private RecyclerArrayAdapter mBaggingAdapter;
    private RecyclerArrayAdapter mStorageAdapter;
    private ListPopWindow listBaggingPopWindow;
    private ListPopWindow listStoragePopWindow;
    private int position = 0; // 选择规格位置临时标记

    private RealTimePriceVO realTimePriceVO;
    private String priceId;
    private String type = "0";
    private String packingCode = "", storageCode = "", standardCode = "";

    private RealPriceDetailsVO realPriceDetailsVO;
    private List<RealTimeListVO> realTimeListVOList = new ArrayList<>();
    private List<PackingVO> packingVOList = new ArrayList<>();
    private List<StorageModeVO> storageModeVOList = new ArrayList<>();
    private List<StandardVO> standardVOList = new ArrayList<>();

    private List<String> xYears = new ArrayList<>();

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_real_time_price_details);
    }

    @Override
    public void initMember() {
        initPopupWindow();
        setWeekSelected();
        if (getIntent().hasExtra("RealTimePriceVO")) {
            realTimePriceVO = (RealTimePriceVO) getIntent().getSerializableExtra("RealTimePriceVO");
            if (null == realTimePriceVO)
                return;
            priceId = realTimePriceVO.getId();
//            standardCode = realTimePriceVO.getFarmProductStandard().getCode();
//            packingCode = realTimePriceVO.getFarmProductPacking().getCode();
//            storageCode = realTimePriceVO.getFarmProductStorageMode().getCode();
            getDetailsData();
        }
//        initData();
        initStartTimePicker();
        initEndTimePicker();
        initLineChart();
    }

    /**
     * 套袋、存贮
     */
    private void initPopupWindow() {
        mStorageAdapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new StorageHolder(parent);
            }

        };
        mBaggingAdapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new BaggingHolder(parent);
            }

        };
    }

    /**
     * 从网络获取实时价格详情
     */
    private void getDetailsData() {
        BusinessRealTimePrice.realPriceDetailsForApp(this, priceId, mStartDate, mEndDate, type, standardCode, packingCode, storageCode, mHandler);
    }

    /**
     * 设置线性表格
     */
    private void initLineChart() {

        mChart.setDrawGridBackground(false);
        mChart.setNoDataText("正在加载");

        // no description text
        mChart.getDescription().setEnabled(false);

        // enable touch gestures
        mChart.setTouchEnabled(true);

        // enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(true);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart

        XAxis xAxis = mChart.getXAxis();
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xYears.get((int) value % xYears.size());
            }
        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        leftAxis.setAxisMaximum(20f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        leftAxis.setDrawZeroLine(false);
//        leftAxis.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//                DecimalFormat df = new DecimalFormat("#.00");
//                return df.format(value);
//            }
//        });


        // limit lines are drawn behind data (and not on top)
        leftAxis.setDrawLimitLinesBehindData(true);

        mChart.getAxisRight().setEnabled(false);

        // add data
//        setData(realTimeListVOList);

        mChart.animateX(2500);

        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();

        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);

        // // dont forget to refresh the drawing
        mChart.invalidate();

    }

    private void setData(List<RealTimeListVO> listVOs) {


        if (listVOs == null || listVOs.size() == 0) {
            mChart.setData(new LineData());
            mChart.getLineData().notifyDataChanged();
            mChart.notifyDataSetChanged();
            mChart.invalidate();
            return;
        }

        if (xYears.size() > 0) //清除已有x轴的数据
            xYears.clear();

        mChart.clear();


        ArrayList<Entry> entriesH = new ArrayList<>();
        ArrayList<Entry> entriesL = new ArrayList<>();

        for (int i = 0; i < listVOs.size(); i++) {
            entriesH.add(new Entry(i, Float.parseFloat(listVOs.get(i).getHighPrice())));
            entriesL.add(new Entry(i, Float.parseFloat(listVOs.get(i).getLowPrice())));
            xYears.add(DateUtil.StringToString(listVOs.get(i).getDate(), DateStyle.MM_DD_EN));
        }

        LineDataSet set1, set2;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set2 = (LineDataSet) mChart.getData().getDataSetByIndex(1);
            set1.setValues(entriesH);
            set2.setValues(entriesL);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(entriesH, "最高价格");

            // set the line to be drawn like this "- - - - - -"
            set1.enableDashedLine(10f, 5f, 0f);
            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(getResources().getColor(R.color.app_color));
            set1.setCircleColor(getResources().getColor(R.color.app_color));
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            set1.setDrawCircleHole(true);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(true);
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);
            set1.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                    DecimalFormat df = new DecimalFormat("#.00");
                    return df.format(entry.getY());
                }
            });
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);

            set2 = new LineDataSet(entriesL, "最低价格");

            // set the line to be drawn like this "- - - - - -"
            set2.enableDashedLine(10f, 5f, 0f);
            set2.enableDashedHighlightLine(10f, 5f, 0f);
            set2.setColor(getResources().getColor(R.color.colorOrange));
            set2.setCircleColor(getResources().getColor(R.color.colorOrange));
            set2.setLineWidth(1f);
            set2.setCircleRadius(3f);
            set2.setDrawCircleHole(true);
            set2.setValueTextSize(9f);
            set2.setDrawFilled(true);
            set2.setFormLineWidth(1f);
            set2.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set2.setFormSize(15.f);
            set2.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                    DecimalFormat df = new DecimalFormat("#.00");
                    return df.format(entry.getY());
                }
            });
            set2.setMode(LineDataSet.Mode.CUBIC_BEZIER);

            if (Utils.getSDKInt() >= 18) {
                // fill drawable only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_9bdada);
                set1.setFillDrawable(drawable);
            } else {
                set1.setFillColor(Color.parseColor("#9BDADA"));
            }

            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            dataSets.add(set1); // add the datasets
            dataSets.add(set2);

            // create a data object with the datasets
            LineData data = new LineData(dataSets);

            // set data
            mChart.setData(data);
            mChart.getLineData().notifyDataChanged();
            mChart.notifyDataSetChanged();
            mChart.invalidate();
        }
    }


    @Override
    public void addListener() {
        mBaggingAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (null != packingVOList && packingVOList.size() > 0) {
                    priceDetailTvBagging.setText(packingVOList.get(position).getPackingName());
//                    packingCode = packingVOList.get(position).getCode();
                }
                if (null != listBaggingPopWindow)
                    listBaggingPopWindow.dismiss();
                BusinessRealTimePrice.realPriceDetailsForApp(RealTimePriceDetailsActivity.this, priceId, mStartDate, mEndDate, type, standardCode, packingCode, storageCode, mHandler);
            }
        });

        mStorageAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (null != storageModeVOList && storageModeVOList.size() > 0) {
                    priceDetailTvStorage.setText(storageModeVOList.get(position).getStorageModeName());
//                    storageCode = storageModeVOList.get(position).getCode();
                }
                if (null != listStoragePopWindow)
                    listStoragePopWindow.dismiss();
                BusinessRealTimePrice.realPriceDetailsForApp(RealTimePriceDetailsActivity.this, priceId, mStartDate, mEndDate, type, standardCode, packingCode, storageCode, mHandler);
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_REAL_PRICE_DETAILS_FOR_APP_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_REAL_PRICE_DETAILS_FOR_APP_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(final Object object) {

        new Thread() {
            public void run() {
                realPriceDetailsVO = FastJsonUtil.getBean(object.toString(), "body", "pl", RealPriceDetailsVO.class);
                // 价格列表绘制图形使用
                realTimeListVOList = FastJsonUtil.getListBean(object.toString(), "body", "realTimeList", RealTimeListVO.class);
                // standardVOList = FastJsonUtil.getListBean(object.toString(), "body", "standardList", StandardVO.class); //暂时不用 数据返回空
                // storageModeVOList = FastJsonUtil.getListBean(object.toString(), "body", "storageModeList", StorageModeVO.class); // 有数据 暂时不用
                // packingVOList = FastJsonUtil.getListBean(object.toString(), "body", "packingList", PackingVO.class);  //暂时不用 数据返回空
                mHandler.post(runnableUi);
            }
        }.start();


//        String standard = FastJsonUtil.getString(object.toString(), "Standard");
//        String storageMode = FastJsonUtil.getString(object.toString(), "StorageMode");
//        String packing = FastJsonUtil.getString(object.toString(), "Packing");

//        if (null != realPriceDetailsVO)
//            setContent();
//        if (null != realTimeListVOList)
//            setData(realTimeListVOList);
//        if (null != packingVOList && packingVOList.size() > 0)
//            setPacking();
//        if (null != storageModeVOList && storageModeVOList.size() > 0)
//            setStorage();

    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            if (null != realPriceDetailsVO)
                setContent();
            if (null != realTimeListVOList)
                setData(realTimeListVOList);
        }

    };

    /**
     * 存贮数据
     */
    private void setStorage() {

        if (listStoragePopWindow == null)
            listStoragePopWindow = new ListPopWindow(this, mStorageAdapter);
        if (mStorageAdapter.getAllData().size() > 0)
            mStorageAdapter.clear();

        mStorageAdapter.addAll(storageModeVOList);

    }

    /**
     * 套袋数据
     */
    private void setPacking() {
        if (listBaggingPopWindow == null)
            listBaggingPopWindow = new ListPopWindow(this, mBaggingAdapter);
        if (mBaggingAdapter.getAllData().size() > 0)
            mBaggingAdapter.clear();
        mBaggingAdapter.addAll(packingVOList);
    }

    private void setContent() {
        setTitle(null == realPriceDetailsVO.getProduceCode() ? "" : TextUtils.isEmpty(realPriceDetailsVO.getProduceCode().getName()) ? "" : realPriceDetailsVO.getProduceCode().getName());
        priceDetailTvStandard.setText(null == realPriceDetailsVO.getFarmProductStandard() ? "" : TextUtils.isEmpty(realPriceDetailsVO.getFarmProductStandard().getStandardName()) ? "" : realPriceDetailsVO.getFarmProductStandard().getStandardName());
        priceDetailIvUpdateDate.setText(String.format("%s", DateUtil.StringToString(TextUtils.isEmpty(realPriceDetailsVO.getCollectDate()) ? "" : realPriceDetailsVO.getCollectDate(), DateStyle.YYYY_MM_DD_EN_HH_MM_EN)));
        priceDetailTvWholesaleMarket.setText(null == realPriceDetailsVO.getFarmProductMarket() ? "" : TextUtils.isEmpty(realPriceDetailsVO.getFarmProductMarket().getMarketName()) ? "" : realPriceDetailsVO.getFarmProductMarket().getMarketName());
        priceDetailTvHighestPrice.setText(TextUtils.isEmpty(realPriceDetailsVO.getHighPrice()) ? "0.00" : com.digitalchina.lxnsy.toolkit.Utils.formatPrice(realPriceDetailsVO.getHighPrice()));
        priceDetailTvUpNumber.setText(TextUtils.isEmpty(realPriceDetailsVO.getHighPriceLimit()) ? "0.00" : com.digitalchina.lxnsy.toolkit.Utils.formatPrice(realPriceDetailsVO.getHighPriceLimit()));
        priceDetailTvUpPercent.setText(String.format("%s%%", TextUtils.isEmpty(realPriceDetailsVO.getHighPriceRange()) ? "0.00" : com.digitalchina.lxnsy.toolkit.Utils.formatPrice(realPriceDetailsVO.getHighPriceRange())));
        priceDetailTvLowestPrice.setText(TextUtils.isEmpty(realPriceDetailsVO.getLowPrice()) ? "0.00" : com.digitalchina.lxnsy.toolkit.Utils.formatPrice(realPriceDetailsVO.getLowPrice()));
        priceDetailTvDownNumber.setText(TextUtils.isEmpty(realPriceDetailsVO.getLowPriceLimit()) ? "0.00" : com.digitalchina.lxnsy.toolkit.Utils.formatPrice(realPriceDetailsVO.getLowPriceLimit()));
        priceDetailTvDownPercent.setText(String.format("%s%%", TextUtils.isEmpty(realPriceDetailsVO.getLowPriceRange()) ? "0.00" : com.digitalchina.lxnsy.toolkit.Utils.formatPrice(realPriceDetailsVO.getLowPriceRange())));
        priceDetailTvBagging.setText(null == realPriceDetailsVO.getFarmProductPacking() ? "" : TextUtils.isEmpty(realPriceDetailsVO.getFarmProductPacking().getPackingName()) ? "" : realPriceDetailsVO.getFarmProductPacking().getPackingName());
        priceDetailTvStorage.setText(null == realPriceDetailsVO.getFarmProductStorageMode() ? "" : TextUtils.isEmpty(realPriceDetailsVO.getFarmProductStorageMode().getStorageModeName()) ? "" : realPriceDetailsVO.getFarmProductStorageMode().getStorageModeName());
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.price_detail_tv_details_data, R.id.price_detail_tv_bagging, R.id.price_detail_tv_storage,
            R.id.layout_real_time_price_tv_week, R.id.layout_real_time_price_tv_month, R.id.layout_real_time_price_tv_custom,
            R.id.price_detail_iv_left, R.id.price_detail_iv_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.price_detail_tv_details_data: // 详细数据
                Map<String, String> map = new HashMap<>();
//                map.put("standardCode", standardCode);
//                map.put("packingCode", packingCode);
//                map.put("storageCode", storageCode);
                if (realPriceDetailsVO == null)
                    return;
                map.put("priceId", realPriceDetailsVO.getId());
                map.put("title", null == realPriceDetailsVO.getProduceCode() ? "暂无" : realPriceDetailsVO.getProduceCode().getName() == null ? "暂无" : realPriceDetailsVO.getProduceCode().getName());
                GotoUtil.gotoActivity(this, RealTimePriceDataDetailsActivity.class, "map", map);
                break;
            case R.id.price_detail_tv_bagging: // 套袋
                showBaggingPopupWindow();
                break;
            case R.id.price_detail_tv_storage: // 存贮
                showStoragePopupWindow();
                break;
            case R.id.price_detail_iv_left: // 向左选择规格
                setStandard("left");
                break;
            case R.id.price_detail_iv_right: // 向右选择规格
                setStandard("right");
                break;
            case R.id.layout_real_time_price_tv_week: // 周
                type = "0";
                setWeekSelected();
                BusinessRealTimePrice.realPriceDetailsForApp(this, priceId, mStartDate, mEndDate, type, standardCode, packingCode, storageCode, mHandler);
                break;
            case R.id.layout_real_time_price_tv_month: // 月
                type = "1";
                setMonthSelected();
                BusinessRealTimePrice.realPriceDetailsForApp(this, priceId, mStartDate, mEndDate, type, standardCode, packingCode, storageCode, mHandler);
                break;
            case R.id.layout_real_time_price_tv_custom: // 自定义
                type = "3";
                setCustomSelected();
                pvStartTime.show();
                break;
        }
    }

    /**
     * 周选中状态
     */
    private void setWeekSelected() {
        layoutRealTimePriceTvWeek.setBackgroundResource(R.color.app_color);
        layoutRealTimePriceTvWeek.setTextColor(getResources().getColor(R.color.colorWhite));
        layoutRealTimePriceTvMonth.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvMonth.setTextColor(getResources().getColor(R.color.app_color));
        layoutRealTimePriceTvCustom.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvCustom.setTextColor(getResources().getColor(R.color.app_color));
        mStartDate = "";
        mEndDate = "";
    }

    /**
     * 月 选中状态
     */
    private void setMonthSelected() {
        layoutRealTimePriceTvWeek.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvWeek.setTextColor(getResources().getColor(R.color.app_color));
        layoutRealTimePriceTvMonth.setBackgroundResource(R.color.app_color);
        layoutRealTimePriceTvMonth.setTextColor(getResources().getColor(R.color.colorWhite));
        layoutRealTimePriceTvCustom.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvCustom.setTextColor(getResources().getColor(R.color.app_color));
        mStartDate = "";
        mEndDate = "";
    }

    /**
     * 自定义 选中状态
     */
    private void setCustomSelected() {
        layoutRealTimePriceTvWeek.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvWeek.setTextColor(getResources().getColor(R.color.app_color));
        layoutRealTimePriceTvMonth.setBackgroundResource(R.color.colorWhite);
        layoutRealTimePriceTvMonth.setTextColor(getResources().getColor(R.color.app_color));
        layoutRealTimePriceTvCustom.setBackgroundResource(R.color.app_color);
        layoutRealTimePriceTvCustom.setTextColor(getResources().getColor(R.color.colorWhite));
    }

    /**
     * 设置规格参数
     */
    private void setStandard(String direct) {
        switch (direct) {
            case "left":
                if (position == 0) {
                    showToast("已经到最左边");
                    return;
                }

                if (position > 0)
                    position--;
                priceDetailTvStandard.setText(standardVOList.get(position).getStandardName());
//                standardCode = standardVOList.get(position).getCode();
                BusinessRealTimePrice.realPriceDetailsForApp(this, priceId, mStartDate, mEndDate, type, standardCode, packingCode, storageCode, mHandler);
                break;
            case "right":
                if (position == standardVOList.size() - 1) {
                    showToast("已经到最右边");
                    return;
                }

                if (position < standardVOList.size() - 1)
                    position++;
                priceDetailTvStandard.setText(standardVOList.get(position).getStandardName());
//                standardCode = standardVOList.get(position).getCode();
                BusinessRealTimePrice.realPriceDetailsForApp(this, priceId, mStartDate, mEndDate, type, standardCode, packingCode, storageCode, mHandler);
                break;
        }

    }

    /**
     * 显示存贮
     */
    private void showStoragePopupWindow() {

        listStoragePopWindow.showPopupWindow(priceDetailTvStorage);

    }

    /**
     * 显示套袋
     */
    private void showBaggingPopupWindow() {


        listBaggingPopWindow.showPopupWindow(priceDetailTvBagging);

    }

    /**
     * 显示自定义开始时间选择
     */
    private void initStartTimePicker() {
        Calendar calendar = Calendar.getInstance();

        pvStartTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                mStartDate = DateUtil.DateToString(date, DateStyle.YYYY_MM_DD);
                pvEndTime.show();
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("下一步")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("起始时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(0xff37B5B4)
                .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR))//默认是1900-2100年
                .setDate(DateUtil.StringToDate(DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD)))// 如果不设置的话，默认是系统时间*/
                .setLabel("年", "月", "日", "", "", "")
                .isDialog(false)//是否显示为对话框样式
                .build();
    }

    /**
     * 显示自定义结束时间选择
     */
    private void initEndTimePicker() {
        Calendar calendar = Calendar.getInstance();

        pvEndTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                mEndDate = DateUtil.DateToString(date, DateStyle.YYYY_MM_DD);
                BusinessRealTimePrice.realPriceDetailsForApp(RealTimePriceDetailsActivity.this, priceId, mStartDate, mEndDate, type, standardCode, packingCode, storageCode, mHandler);
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("完成")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("结束时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(0xff37B5B4)
                .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR))//默认是1900-2100年
                .setDate(DateUtil.StringToDate(DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD)))// 如果不设置的话，默认是系统时间*/
                .setLabel("年", "月", "日", "", "", "")
                .isDialog(false)//是否显示为对话框样式
                .build();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (pvStartTime != null && pvStartTime.isShowing()) {
            pvStartTime.dismiss();
            return true;
        } else if (pvEndTime != null && pvEndTime.isShowing()) {
            pvEndTime.dismiss();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
